# -*- coding: utf-8 -*-

"""
工具库：手册结构解析
"""

import os


def parse2(structure_define):
    """ 解析结构定义 """
    if isinstance(structure_define, str):
        return {'name': structure_define, 'title': structure_define, 'books': []}
    return {
        'name': structure_define[0],
        'title': structure_define[1],
        'books': [parse(i) for i in structure_define[2]]
    }


def parse(structure, parent='', book_dir='./'):
    """
    根据书籍结构信息获取 SUMMARY.md 文件列表

    [
        '', '', [
            ['', '', []]
        ]
    ]
    """
    books = []
    name = structure[0]
    for substructure in structure[2]:
        if isinstance(substructure, (list, tuple)):
            book = os.path.join(parent, name, substructure[0])
            if not book_dir or os.path.isfile(os.path.abspath(os.path.join(book_dir, book, 'SUMMARY.md'))):
                books.append(book)
            books.extend(parse(substructure, parent=os.path.join(parent, name), book_dir=book_dir))
        elif isinstance(substructure, str):
            book = os.path.join(parent, name, substructure)
            books.append(book)
        else:
            print 'WARN: data error %r' % substructure
    return [i.replace('\\', '/') for i in books]


def get_names(structure_define, parent=''):
    """ 从结构定义中解析出名称映射 """
    dct = {}
    if not isinstance(structure_define, list):
        print structure_define
        return dct
    book_key = (parent + '/' + structure_define[0]) if parent else structure_define[0]
    dct[book_key] = structure_define[1]
    for i in structure_define[2]:
        if not isinstance(i, list):
            # print '>>>', i
            continue
        dct.update(get_names(i, parent=book_key))
    return dct
